package com.atguigu.gmall.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.oms.entity.OrderItemEntity;
import com.atguigu.gmall.oms.feign.GmallPmsClient;
import com.atguigu.gmall.oms.service.OrderItemService;
import com.atguigu.gmall.oms.vo.OrderItemVo;
import com.atguigu.gmall.oms.vo.OrderSubmitVo;
import com.atguigu.gmall.pms.api.GmallPmsApi;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.oms.mapper.OrderMapper;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {
    @Autowired
    private GmallPmsClient pmsClient;
    @Autowired
    private OrderItemService orderItemService;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<OrderEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<OrderEntity>()
        );

        return new PageResultVo(page);
    }

    @Transactional
    @Override
    public void saveOrder(OrderSubmitVo submitVo, Long userId) {
            //1.新增订单信息
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setUserId(userId); //用户id
            orderEntity.setOrderSn(submitVo.getOrderToken()); //订单号
            orderEntity.setCreateTime(new Date()); //创建时间
            orderEntity.setTotalAmount(submitVo.getTotalPrice()); // 订单总额
            // TODO：应付金额：应该经过复杂计算，这里我们就取订单总金额
            orderEntity.setPayAmount(submitVo.getTotalPrice()); //应付总额
            // 购物积分
            Integer bounds = submitVo.getBounds();
            // 100个积分抵一元
            orderEntity.setIntegrationAmount(new BigDecimal(bounds/100)); // 积分抵扣金额
            orderEntity.setPayType(submitVo.getPayType()); //支付方式 【1->支付宝；2->微信；3->银联； 4->货到付款；】
            orderEntity.setSourceType(0); // 订单来源[0->PC订单；1->app订单]
            orderEntity.setStatus(0);  //订单状态
            orderEntity.setDeliveryCompany(submitVo.getDeliveryCompany()); // 物流公司
            // TODO: 根据送货清单中的skuId查询积分
            orderEntity.setIntegration(0); // 可以获得的积分
            orderEntity.setGrowth(0); // 可以获得的成长值
            // 设置物流信息
            UserAddressEntity address = submitVo.getAddress();
            if (address != null){
                orderEntity.setReceiverAddress(address.getAddress());
                orderEntity.setReceiverCity(address.getCity()); // 收货人城市
                orderEntity.setReceiverName(address.getName()); // 收货人姓名
                orderEntity.setReceiverPhone(address.getPhone()); // 收货人电话
                orderEntity.setReceiverPostCode(address.getPostCode()); // 收货人邮编
                orderEntity.setReceiverProvince(address.getProvince()); // 收货人所在省份/直辖市
                orderEntity.setReceiverRegion(address.getRegion()); // 收货人所在区
            }
            orderEntity.setConfirmStatus(0); //确认收货状态 0: 未确认, 1: 已确认
            orderEntity.setDeleteStatus(0); // 删除状态 0:未删除 , 1: 已删除
            orderEntity.setUseIntegration(submitVo.getBounds()); //下单时使用的积分
        //2.新增订单详情信息
        List<OrderItemVo> items = submitVo.getItems();
        if (!CollectionUtils.isEmpty(items)){
            List<OrderItemEntity> itemEntities = items.stream().map(orderItemVo -> {
                OrderItemEntity itemEntity = new OrderItemEntity();
                itemEntity.setOrderId(orderEntity.getId());
                itemEntity.setOrderSn(submitVo.getOrderToken());
                itemEntity.setSkuQuantity(orderItemVo.getCount().intValue());
                // 查询sku相关信息
                ResponseVo<SkuEntity> skuEntityResponseVo = this.pmsClient.querySkuById(orderItemVo.getSkuId());
                SkuEntity skuEntity = skuEntityResponseVo.getData();
                if (skuEntity != null) {
                    itemEntity.setSkuId(skuEntity.getId());
                    itemEntity.setSkuName(skuEntity.getName());
                    itemEntity.setSkuPic(skuEntity.getDefaultImage());
                    itemEntity.setSkuPrice(skuEntity.getPrice());
                    itemEntity.setCategoryId(skuEntity.getCategoryId());
                }
                //查询spu
                ResponseVo<SpuEntity> spuEntityResponseVo = this.pmsClient.querySpuById(skuEntity.getSpuId());
                SpuEntity spuEntity = spuEntityResponseVo.getData();
                if (spuEntity != null) {
                    itemEntity.setSpuId(skuEntity.getSpuId());
                    itemEntity.setSpuName(spuEntity.getName());
                }
                // 查询spu描述
                ResponseVo<SpuDescEntity> spuDescEntityResponseVo = this.pmsClient.querySpuDescById(spuEntity.getId());
                SpuDescEntity spuDescEntity = spuDescEntityResponseVo.getData();
                if (spuDescEntity != null) {
                    itemEntity.setSpuPic(spuDescEntity.getDecript());
                }
                // 查询品牌
                ResponseVo<BrandEntity> brandEntityResponseVo = this.pmsClient.queryBrandById(skuEntity.getBrandId());
                BrandEntity brandEntity = brandEntityResponseVo.getData();
                if (brandEntity != null) {
                    itemEntity.setSpuBrand(brandEntity.getName());
                }
                // 查询销售属性
                ResponseVo<List<SkuAttrValueEntity>> saleAttrResponseVo = this.pmsClient.querySaleAttrValueBySkuId(skuEntity.getId());
                List<SkuAttrValueEntity> attrValueEntities = saleAttrResponseVo.getData();
                itemEntity.setSkuAttrsVals(JSON.toJSONString(attrValueEntities));

                // todo: 查询积分赠送信息
                return itemEntity;
            }).collect(Collectors.toList());
            this.orderItemService.saveBatch(itemEntities);
        }
    }
}













